package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.query.DestQueryObject;
import cn.wolfcode.luowowo.search.query.IndexSearchQuery;
import cn.wolfcode.luowowo.search.repository.DestinationTemplateRepository;
import cn.wolfcode.luowowo.search.service.IDestinationSearchService;
import cn.wolfcode.luowowo.search.service.SearchQueryService;
import cn.wolfcode.luowowo.search.template.DestinationTemplate;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

/**
 * @author 猫教授
 * @date 2019/8/18 17:18
 */
@Service
public class DestinationSearchServiceImpl implements IDestinationSearchService{
    //操作se搜索引擎的共有三个操作方式,分别con底层到上层
    //第一种,是repository接口
    @Autowired
    private DestinationTemplateRepository repository;
    //第二种是template
    @Autowired
    private ElasticsearchTemplate template;
    //第三种是最底层的
    @Autowired
    private TransportClient client;
    @Autowired
    private SearchQueryService searchQueryService;


    @Override
    public void saveOrUpdate(DestinationTemplate ttt) {
        repository.save(ttt);
    }

    @Override
    public DestinationTemplate findByName(String keyword) {
        return repository.findByName(keyword);
    }

    @Override
    public AggregatedPage<DestinationTemplate> selectByKeyword(IndexSearchQuery qo,String...fieldName) {

        return searchQueryService.selectByKeyword(qo,"<span style='color:red;'>","</span>",DestinationTemplate.class,DestinationTemplate.INDEX_NAME,DestinationTemplate.TYPE_NAME,fieldName);
    }

    public Page<DestinationTemplate> selectByTheme(DestQueryObject qo){
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //指定查询具体哪个表
        builder.withIndices("luowowo_destination");
        builder.withTypes("destination");
        //分页排序
        builder.withPageable(qo.getPageable());
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if(qo.getTime()!=-1) {
            queryBuilder.must(QueryBuilders.matchQuery("time", qo.getTime()));
        }
        if(qo.getTheme()!=-1){
            queryBuilder.must(QueryBuilders.matchQuery("theme", qo.getTheme()));
        }
        if(qo.getDay()!=-1){
            queryBuilder.must(QueryBuilders.termQuery("day", qo.getDay()));
        }

        builder.withQuery(queryBuilder);
        Page<DestinationTemplate> search = repository.search(builder.build());
        return search;
    }
}
